import axios from 'axios'
import MD5 from 'crypto-js/md5'
import { NODE_ENV } from 'common/js/process'
import { API, API_TIMESTAMP, ERR_CODE } from 'api/config'

export const RefreshLogin = `${API}/login/refresh` // 刷新登录
export const EmailLogin = `${API}/login` // 邮箱登录
export const PhoneLogin = `${API}/login/cellphone` // 手机号&密码登录
export const CaptchaSent = `${API}/captcha/sent` // 发送验证码
export const CaptchaVerify = `${API}/captcha/verify` // 验证码登录

export const StatusAsync = `${API}/login/status` // 登录状态
export const LogoutAsync = `${API}/logout` // 退出登录

/* 刷新登录 */
export function RefreshLoginAsync () {
  const url = NODE_ENV === 'production' ? API_TIMESTAMP(RefreshLogin) : RefreshLogin
  // const url = API_TIMESTAMP(RefreshLogin)

  return axios.post(url).then(res => {
    if (res.code === ERR_CODE) {
      return Promise.resolve(res)
    } else {
      return Promise.reject(res.msg)
    }
  }).catch(err => {
    return Promise.reject(err)
  })
}

/* 邮箱登录 */
export function EmailLoginAsync ({ email, password }) {
  const url = API_TIMESTAMP(EmailLogin)

  return axios.post(url, { email, md5_password: MD5(password).toString() }).then(LoginThen).catch(err => Promise.reject(err))
}

export function PhoneLoginAsync ({ phone, password, captcha }) {
  const data = { phone }
  if (password) {
    data.md5_password = MD5(password).toString()
  } else {
    data.captcha = captcha
  }
  const url = API_TIMESTAMP(PhoneLogin)

  return axios.post(url, data).then(LoginThen).catch(err => Promise.reject(err))
}

export function SendCaptcha (phone) {
  return axios.post(CaptchaSent, { phone }).then(res => {
    if (res.code === ERR_CODE) {
      return Promise.resolve(res)
    } else {
      return Promise.reject(res.msg)
    }
  }).catch(err => {
    return Promise.reject(err)
  })
}

function LoginThen (res) {
  if (res.code === ERR_CODE) {
    return Promise.resolve(res)
  } else {
    const data = {msg: res.msg}
    return Promise.reject(data)
  }
}

export function getStatus () {
  const url = StatusAsync // API_TIMESTAMP(StatusAsync)
  return axios.post(url, null, {
    withCredentials: true
  }).then(res => {
    if (res.data.code === ERR_CODE) {
      return Promise.resolve(res.data)
    } else {
      return Promise.reject(res.msg)
    }
  }).catch(err => {
    return Promise.reject(err)
  })
}

export function Logout () {
  return axios.post(LogoutAsync)
}
